package com.killer.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.killer.order.service.ICartService;
import com.killer.common.entity.Result;
import com.killer.goods.entity.Sku;
import com.killer.goods.entity.Spu;
import com.killer.goods.feign.SkuClient;
import com.killer.goods.feign.SpuClient;
import com.killer.order.dto.OrderItemDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Killer
 * @title: CartServiceImpl
 * @projectName shop-parent
 * @description: TODO
 * @date 2021/11/1 15:54
 */
@Service
public class CartServiceImpl implements ICartService {

    private final static String CART_NAMESPACE = "CART_";
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SpuClient spuClient;
    @Autowired
    private SkuClient skuClient;

    /**
     * 添加购物车
     *
     * @param userId
     * @param skuId
     * @param num
     */
    @Override
    public void add(Long userId, Long skuId, Integer num) {
        //如果传过来的num是0，就删除该商品
        if (num <= 0) {
            redisTemplate.boundHashOps(CART_NAMESPACE + userId).delete(String.valueOf(skuId));
            return;
        }
        OrderItemDTO orderItemDTO = null;
        //判断购物车中是否存在了该商品
        Object cacheValues = redisTemplate.boundHashOps(CART_NAMESPACE + userId).get(String.valueOf(skuId));
        if (cacheValues != null) {
            orderItemDTO = JSONObject.parseObject(cacheValues.toString(), OrderItemDTO.class);
            orderItemDTO.setNum(num);
            orderItemDTO.setMoney(orderItemDTO.getNum() * orderItemDTO.getPrice());
            orderItemDTO.setPayMoney(orderItemDTO.getNum() * orderItemDTO.getPrice());
        } else {
            //访问商品微服务获得SKU,SPU
            Result<Sku> skuResult = skuClient.findById(skuId);
            if (skuResult == null || skuResult.getData() == null) {
                throw new RuntimeException(skuId + "该sku不存在");
            }
            Sku sku = skuResult.getData();
            //查询spu
            Result<Spu> spuResult = spuClient.findById(sku.getSpuId());
            if (spuResult == null || spuResult.getData() == null) {
                throw new RuntimeException(skuId + "该sku对应的spu不存在");
            }
            Spu spu = spuResult.getData();
            //转换为orderItem
            orderItemDTO = parseToOrerItemDTO(spu, sku, num);
        }
        //保存
        redisTemplate.boundHashOps(CART_NAMESPACE + userId).put(String.valueOf(skuId), JSONObject.toJSONString(orderItemDTO));
    }

    private OrderItemDTO parseToOrerItemDTO(Spu spu, Sku sku, Integer num) {
        OrderItemDTO orderItemDTO = new OrderItemDTO();
        orderItemDTO.setCategoryId1(spu.getCategory1Id());
        orderItemDTO.setCategoryId2(spu.getCategory2Id());
        orderItemDTO.setCategoryId3(spu.getCategory3Id());
        orderItemDTO.setSpuId(spu.getId());
        orderItemDTO.setSkuId(sku.getId());
        orderItemDTO.setName(sku.getName());
        orderItemDTO.setPrice(sku.getPrice());
        orderItemDTO.setNum(num);
        orderItemDTO.setMoney(num * orderItemDTO.getPrice());//Num * price
        orderItemDTO.setPayMoney(num * orderItemDTO.getPrice());
        orderItemDTO.setImage(sku.getImage());
        orderItemDTO.setWeight(sku.getWeight() * num);
        return orderItemDTO;
    }

    /**
     * 查询购物车
     * @param userId
     * @return
     */
    @Override
    public Map<String,Object>  list(Long userId) {
        //定义返回结果
        Map<String, Object> resultMap = new HashMap<>();
        //商品总数及商品总的价格
        Integer totalNum = 0;
        Integer totalPrice = 0;
        List<OrderItemDTO> orderItemDTOList = new ArrayList<>();
        //读取
        List<String> cacheValues = redisTemplate.boundHashOps(CART_NAMESPACE + userId).values();
        if (CollectionUtils.isNotEmpty(cacheValues)) {
            for (String cacheValue : cacheValues) {
                OrderItemDTO orderItemDTO = JSONObject.parseObject(cacheValue, OrderItemDTO.class);
                orderItemDTOList.add(orderItemDTO);
                totalNum += orderItemDTO.getNum();
                totalPrice+=orderItemDTO.getMoney();
            }
        }
        resultMap.put("orderItemList", orderItemDTOList);
        resultMap.put("totalNum", totalNum);
        resultMap.put("totalPrice",totalPrice);
        return resultMap;
    }

    /**
     * 删除购物车
     * @param userId
     * @param skuId
     */
    @Override
    public void delete(Long userId, Long skuId) {
        redisTemplate.boundHashOps(CART_NAMESPACE + userId).delete(String.valueOf(skuId));
    }

    /**
     * 更改购物车勾选状态
     * @param userId
     * @param skuId
     * @param checked
     */
    @Override
    public void updateCheckedStatus(Long userId, Long skuId, Boolean checked) {
        Object cacheValues = redisTemplate.boundHashOps(CART_NAMESPACE + userId).get(String.valueOf(skuId));
        if (cacheValues != null) {
            OrderItemDTO orderItemDTO = JSONObject.parseObject(cacheValues.toString(), OrderItemDTO.class);
            orderItemDTO.setChecked(checked);
            redisTemplate.boundHashOps(CART_NAMESPACE+userId).put(String.valueOf(skuId),JSONObject.toJSONString(orderItemDTO));
        }
    }

}
